/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.utils.DateUtils;
import com.yuhanginfo.common.utils.FileUtils;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.common.utils.excel.ExportExcel;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.Goodsplatformmanger;
import com.yuhanginfo.modules.sys.entity.Materiel;
import com.yuhanginfo.modules.sys.entity.Vender;
import com.yuhanginfo.modules.sys.service.GoodsService;
import com.yuhanginfo.modules.sys.service.MaterielService;
import com.yuhanginfo.modules.sys.service.VenderService;
import com.yuhanginfo.modules.sys.utils.UserUtils;

/**
 * 商品管理
 * @author yinhao
 * @version 2017-09-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/goodsplatformmanger/")
public class GoodsController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private MaterielService materielService;
	
	@Autowired
	private VenderService venderService;
	
	private static final  String IMAGE = "image";
	
	private static final  String DETAIL = "detail";
	
	private static final  String SERVICE = "service";
	@ModelAttribute
	public Goods get(@RequestParam(required = false) String id) {
		Goods entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = goodsService.get(id);
		}
		if (entity == null) {
			entity = new Goods();
		}
		return entity;
	}

	@RequiresPermissions("sys:goodsplatformmanger:view")
	@RequestMapping(value = { "list", "" })
	public String list(Goods goods, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Goods> page = goodsService.findPage(new Page<Goods>(request, response), goods);
		model.addAttribute("page", page);
		//制造商品牌
		List<Vender> venderList = venderService.findList(new Vender());
		model.addAttribute("venderList",venderList);
		return "modules/sys/goodsplatformmanger/goodsList";
	}

	@RequiresPermissions("sys:goodsplatformmanger:view")
	@RequestMapping(value = "form")
	public String form(Goods goods, Model model) {
		Materiel materiel = new Materiel();
		Goods resultGoods = new Goods();
		if( goods.getId() != null){
		    resultGoods = goodsService.get(goods);
			Materiel queryMateriel = new Materiel();
			queryMateriel.setCode(resultGoods.getMaterielCode());
			materiel = materielService.get(queryMateriel);
		}
		model.addAttribute("goods", resultGoods);
		model.addAttribute("materiel", materiel);
		return "modules/sys/goodsplatformmanger/goodsForm";
	}
	
	@RequiresPermissions("sys:goodsplatformmanger:view")
	@RequestMapping(value = "view")
	public String view(Goods goods, Model model) {
		Materiel materiel = new Materiel();
		Goods resultGoods = new Goods();
		if( goods.getId() != null){
			resultGoods = goodsService.get(goods);
			Materiel queryMateriel = new Materiel();
			queryMateriel.setCode(resultGoods.getMaterielCode());
			materiel = materielService.get(queryMateriel);
		}
		model.addAttribute("goods", resultGoods);
		model.addAttribute("materiel", materiel);
		return "modules/sys/goodsplatformmanger/goodsView";
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "save")
	public String save(Goods goods, Model model, HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		String[] imageSelect = request.getParameterValues("imageSelect");
		String[] detailSelect = request.getParameterValues("detailSelect");
		String[] serviceSelect = request.getParameterValues("serviceSelect");
		if (!beanValidator(model, goods)) {
			return form(goods, model);
		}
		String image = (String) session.getAttribute(IMAGE);
		session.removeAttribute(IMAGE);
		String detail = (String) session.getAttribute(DETAIL);
		session.removeAttribute(DETAIL);
		String service = (String) session.getAttribute(SERVICE);
		session.removeAttribute(SERVICE);
		try {
			goodsService.save(UserUtils.getUser().getId(), goods, image, detail, service,imageSelect,detailSelect,serviceSelect);
		} catch (Exception ex) {
			logger.info("save",ex);
		}
		model.addAttribute(new Goods());
		return this.list(new Goods(), request, response, model);
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "saveImage")
	@ResponseBody
	public String saveImage(@RequestParam("file") MultipartFile[] file, HttpSession session) {
		StringBuilder path = new StringBuilder();
		try {
			int i = 0;
			for (MultipartFile f : file) {
				if( i > 0 ){
					path.append(";");
				}
				path.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), f.getOriginalFilename(), f.getInputStream()));
				i++;
			}
		} catch (Exception ex) {
			logger.info("saveImage",ex);
		}
		session.setAttribute(IMAGE, path.toString());
		return "true";
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "saveDetail")
	@ResponseBody
	public String saveDetail(@RequestParam("file") MultipartFile[] file, HttpSession session) {
		StringBuilder path = new StringBuilder();
		try {
			int i = 0;
			for (MultipartFile f : file) {
				if( i > 0 ){
					path.append(";");
				}
				path.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), f.getOriginalFilename(), f.getInputStream()));
				i++;
			}
		} catch (Exception ex) {
			logger.info("saveDetail",ex);
		}
		session.setAttribute(DETAIL, path.toString());
		return "true";
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "saveService")
	@ResponseBody
	public String saveService(@RequestParam("file") MultipartFile[] file, HttpSession session) {
		StringBuilder path = new StringBuilder();
		try {
			int i = 0;
			for (MultipartFile f : file) {
				if( i > 0 ){
					path.append(";");
				}
				path.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), f.getOriginalFilename(), f.getInputStream()));
				i++;
			}
		} catch (Exception ex) {
			logger.info("saveService",ex);
		}
		session.setAttribute(SERVICE, path.toString());
		return "true";
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "delete")
	public String delete(Goods goods, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAllAttributes(goodsService.del(goods));
		return this.list(new Goods(), request, response, model);
	}

	@RequiresPermissions("sys:goodsplatformmanger:edit")
	@RequestMapping(value = "batchDelete")
	public String batchDelete(Goods goods,String[] arrayId, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model) {
		try{
			goodsService.batchDel(arrayId);
		}catch(Exception ex){
			logger.info("batchDelete",ex);
		}
		return this.list(goods, request, response, model);
	}

	@RequiresPermissions("sys:goodsplatformmanger:view")
	@RequestMapping(value = "goodsDetail")
	public String goodsDetail(String goodsCode,String storeCode,String tagUrl,String tagName,Model model) {
		Map<String,String> params=new HashMap<>();
		params.put("goodsCode", goodsCode);
		model.addAttribute("goodsDetail", goodsService.getGoodsByCode(params));
		model.addAttribute("tagUrl",tagUrl);
		model.addAttribute("tagName",tagName);
		return "modules/sys/goodsDetail";
	}
	
	@RequiresPermissions("sys:goodsplatformmanger:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Goods goods, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "平台商品管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<Goods> list = goodsService.findList(goods);
    		new ExportExcel("平台商品管理", Goodsplatformmanger.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception ex) {
			logger.info("exportFile",ex);
		}
		return null;
    }
}